//对axios 进行二次封装
import axios from 'axios'
//进度条
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
//id
import { getTempUserUuidToken } from '@/utils/uuidToken'
//引入仓库
import store from '@/store/index'

let requests = null
if (process.env.NODE_ENV == 'production') {
  requests = axios.create({
    baseURL: '/sph/api',
    timeout: 10000
  })
} else {
  requests = axios.create({
    baseURL: '/api',
    timeout: 10000
  })
}

// 请求拦截器
requests.interceptors.request.use((config) => {
  //config 包含 请求头【header】,请求头能否给服务器携带参数
  nprogress.start()
  //携带游客id
  let id = getTempUserUuidToken()
  if (id) {
    config.headers.userTempId = id
  }
  // 携带登录的用户token
  let token = store.state.user.token
  if (token) {
    config.headers.token = token
  }
  return config
})

// 响应拦截器
requests.interceptors.response.use(
  (res) => {
    // 响应成功的回调
    nprogress.done()
    //res axios包装的数据;res.data 服务器返回的数据
    return res.data
  },
  (error) => {
    //响应失败的回调
    nprogress.done()
    console.log(error)
    return Promise.reject(new Error('faile'))
  }
)

//导出
export default requests
